import { createWebHistory, createRouter } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'Home',
    redirect: '/home',
    component: () => import('@/layout/index.vue'),
    children: [
      {
        path: '/user',
        component: () => import('@/views/User/index.vue'),
        params: {
          code: String
        }
      },
      {
        path: '/about',
        component: () => import('@/views/About/index.vue')
      },
      {
        path: '/error',
        component: () => import('@/views/404/index.vue')
      },
      {
        path: '/:uuid(\\d+)',
        component: () => import('@/views/ToDoList/index.vue')
      },
      {
        path: '/:category?',
        component: () => import('@/views/ToDoList/index.vue')
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login/index.vue')
  }
]

const router = createRouter({
  routes,
  history: createWebHistory()
})

const token = () => {
  return new Date().getTime() > +(localStorage.getItem('authTimeout') || 0)
    ? undefined
    : localStorage.getItem('token')
}

router.beforeEach(async (to, from) => {
  if (!token() && to.name !== 'Login' && from.name !== 'Login') {
    localStorage.removeItem('token')
    localStorage.removeItem('authTimeout')
    return { name: 'Login' }
  }
})

export default router
